/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
ACSTree = function() {
    ACSTree.superclass.constructor.call(this, {
        id:'acs-tree',
        region:'west',
        title:'',
        split:true,
        width: 220,
        minSize: 180,
        maxSize: 300,
        collapsible: false,
        margins:'5 0 25 0',
        cmargins:'0 5 5 5',
        rootVisible:false,
        lines:false,
        autoScroll:true,
        root: new Ext.tree.TreeNode('Root'),
        collapseFirst:false,
        tbar:[{
        	id:'group-menu',
            split:false,
            text:'Groups',
            tooltip: {title:'Device Groups'},
			iconCls:'group-icon',
            menu:{
                id:'group-menulist',
                cls:'acs-menu',
                width:105,
                items: [{
                	id: 'newGroup',
                    text: 'New Group',
                    handler: this.showNewGroup,
                    scope: this,
                    iconCls:'new-group-icon'
                },{
                 	id: 'editGroup',
                    text: 'Edit Group',
                    handler: this.showEditGroup,
                    scope: this,
                    iconCls:'edit-group-icon'
                },{
                	id: 'deleteGroup',
                    text:'Delete Group',
                    handler: this.deleteGroup,
                    scope: this,
                    iconCls:'delete-group-icon'
                }]
            }
        },{
        	id:'configuration-menu',
            split:false,
            text:'Configurations',
            tooltip: {title:'Device Configurations'},
			iconCls:'configuration-icon',
            menu:{
                id:'configuration-menulist',
                cls:'acs-menu',
                width:140,
                items: [{
                	id: 'newConfiguration',
                    text: 'New Configuration',
                    handler: this.showNewConfiguration,
                    scope: this,
                    iconCls:'new-configuration-icon'
                },{
                 	id: 'editConfiguration',
                    text: 'Edit Configuration',
                    handler: this.showEditConfiguration,
                    scope: this,
                    iconCls:'edit-configuration-icon'
                },{
                	id: 'deleteConfiguration',
                    text: 'Delete Configuration',
                    handler: this.deleteConfiguration,
                    scope: this,
                    iconCls:'delete-configuration-icon'
                }]
            }
        },{id:'changePassword',
           text:'',
           tooltip: {title:'Change Password'},
           iconCls:'password-icon',        
           handler: this.showChangePassword,
           scope: this
        }]
    });

    this.groups = this.root.appendChild(
        new Ext.tree.TreeNode({
        	id: 'groups',
            text:'Device Groups',
            cls:'acspanel-node',
            expanded:true
        })
    );

    this.configurations = this.root.appendChild(
            new Ext.tree.TreeNode({
            	id: 'configurations',
                text:'Device Configurations',
                cls:'acspanel-node',
                expanded:true
            })
        );

    this.getSelectionModel().on({
        'beforeselect' : function(sm, node){
            return node.isLeaf();
        },
        'selectionchange' : function(sm, node){
            if(node && node.isLeaf()){
            	if(node.attributes.obj.type == 'g') {
	            	this.getTopToolbar().items.get('group-menu').menu.items.get('editGroup').setDisabled(false);
	            	this.getTopToolbar().items.get('group-menu').menu.items.get('deleteGroup').setDisabled(false);
	            	this.getTopToolbar().items.get('configuration-menu').menu.items.get('editConfiguration').setDisabled(true);
	            	this.getTopToolbar().items.get('configuration-menu').menu.items.get('deleteConfiguration').setDisabled(true);
	            	this.groupSelected = node.attributes.obj;
	            	this.configurationSelected = 0;
	            	
            	} else {
	            	this.getTopToolbar().items.get('group-menu').menu.items.get('editGroup').setDisabled(true);
	            	this.getTopToolbar().items.get('group-menu').menu.items.get('deleteGroup').setDisabled(true);
	            	this.getTopToolbar().items.get('configuration-menu').menu.items.get('editConfiguration').setDisabled(false);
	            	this.getTopToolbar().items.get('configuration-menu').menu.items.get('deleteConfiguration').setDisabled(false);
	            	this.groupSelected = 0;
	            	this.configurationSelected = node.attributes.obj;
            	}
            }
            else{
            	this.getTopToolbar().items.get('group-menu').menu.items.get('editGroup').setDisabled(true);
            	this.getTopToolbar().items.get('group-menu').menu.items.get('deleteGroup').setDisabled(true);
            	this.getTopToolbar().items.get('configuration-menu').menu.items.get('editConfiguration').setDisabled(true);
            	this.getTopToolbar().items.get('configuration-menu').menu.items.get('deleteConfiguration').setDisabled(true);
            }            	
        },
        scope:this
    });

    this.groupSelected = 0;
    this.configurationSelected = 0;
	this.getTopToolbar().items.get('group-menu').menu.items.get('editGroup').setDisabled(true);
	this.getTopToolbar().items.get('group-menu').menu.items.get('deleteGroup').setDisabled(true);
    this.getTopToolbar().items.get('configuration-menu').menu.items.get('editConfiguration').setDisabled(true);
    this.getTopToolbar().items.get('configuration-menu').menu.items.get('deleteConfiguration').setDisabled(true);

    this.addEvents({validgroup:true,validconfiguration:true});

    this.on('dblclick', this.onDblClick, this);
    this.on('contextmenu', this.onContextMenu, this);
 
	this.task = Ext.TaskMgr.start({run: this.onTimer, interval: 60000, scope: this});
};

Ext.extend(ACSTree, Ext.tree.TreePanel, {
	onTimer : function() {
		this.refreshGroups();
    	this.refreshConfigurations();    
	},
	
	refresh : function(){
		this.refreshGroups();
		this.refreshConfigurations();
	},

	refreshGroups : function(){
		SGui.getGroups(this.cbRefreshGroups,this);
	},

	cbRefreshGroups : function(obj,result){
		if(result)
		{
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateGroup(result[i]);
			} else {
				obj.updateGroup(result);
			}
		}
	},
	
	refreshConfigurations : function(){
		SGui.getConfigurations(this.cbRefreshConfigurations,this);
	},

	cbRefreshConfigurations : function(obj,result){
		if(result)
		{
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateConfiguration(result[i]);
			} else {
				obj.updateConfiguration(result);
			}
		}
	},

	onDblClick : function(node, e){
		if(node && node.isLeaf()){
           	this.fireEvent('nodeselect', node.attributes.obj);
		}   
	},
	
    onContextMenu : function(node, e){
        if(!this.menu){ 
            this.menu = new Ext.menu.Menu({
                id:'acstree-ctx',
                items: [{
                    id:'cm-new-group',
                    iconCls:'group-icon',
                    text:'New Group',
                    scope: this,
                    handler: this.showNewGroup
                },{
                    id:'cm-new-configuration',
                    iconCls:'configuration-icon',
                    text:'New Configuraiton',
                    scope: this,
                    handler: this.showNewConfiguration
                },'-',{
                    id:'open',
                    iconCls:'open-group-icon',
                    text:'Open',
                    scope: this,
                    handler: this.contextOpen
                },{
                    id:'edit',
                    iconCls:'edit-group-icon',
                    text:'Edit',
                    scope: this,
                    handler: this.contextEdit
                },{
                	id:'remove',
                    text:'Remove',
                    iconCls:'delete-group-icon',
                    scope: this,
                    handler: this.contextRemove
                }]
            });
            
            this.menu.on('hide', this.onContextHide, this);
        }
        
        if(this.ctxNode){
            this.ctxNode.ui.removeClass('x-node-ctx');
            this.ctxNode = null;
        }

        this.ctxNode = node;
        this.ctxNode.ui.addClass('x-node-ctx');
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxNode){
            this.ctxNode.ui.removeClass('x-node-ctx');
            this.ctxNode = null;
        }
    },

	contextOpen : function(){
		this.ctxNode.select();			
		if(this.ctxNode.attributes.obj.type == 'g') {
			this.groupSelected = this.ctxNode.attributes.obj;	
           	this.fireEvent('nodeselect', this.groupSelected);
		} else if(this.ctxNode.attributes.obj.type == 'c'){
			this.configurationSelected = this.ctxNode.attributes.obj;
           	this.fireEvent('nodeselect', this.configurationSelected);
		}
	},

	contextEdit : function(){
		this.ctxNode.select();			
		if(this.ctxNode.attributes.obj.type == 'g') {
			this.groupSelected = this.ctxNode.attributes.obj;	
			this.showEditGroup();
		} else if(this.ctxNode.attributes.obj.type == 'c'){
			this.configurationSelected = this.ctxNode.attributes.obj;
			this.showEditConfiguration();			
		}
	},

	contextRemove : function(){
		this.ctxNode.select();
		if(this.ctxNode.attributes.obj.type == 'g') {
			this.groupSelected = this.ctxNode.attributes.obj;	
			this.deleteGroup();
		} else if(this.ctxNode.attributes.obj.type == 'c'){
			this.configurationSelected = this.ctxNode.attributes.obj;
			this.deleteConfiguration();
		}
	},

	showChangePassword : function(){
        if(!this.winPass){
            this.winPass = new UserWindow();
        }

        this.winPass.show();
	},

	showNewGroup : function(){
        if(!this.winGroup){
            this.winGroup = new GroupWindow();
            this.winGroup.on('validgroup', this.cbGroup, this);
        }

        this.winGroup.show();
	},

	showEditGroup : function(){
        if(!this.winGroup){
            this.winGroup = new GroupWindow();
            this.winGroup.on('validgroup', this.cbGroup, this);
        }

        this.winGroup.show(this.groupSelected);
	},
	
	cbGroup : function(xml){
		this.updateGroup(xml);
       	this.fireEvent('nodereload', new Group(xml));
	},
	
	updateGroup : function(xml){
		var group = new Group(xml);
		var node = this.getNodeById(group.tid)
        if(node) {
        	node.setText(group.text);
        	node.attributes.obj = group;
        	this.groupSelected = group;
        } else {
	        this.groups.appendChild(new Ext.tree.TreeNode({ iconCls: 'group-icon', leaf:true, cls:'group-node', id: group.tid, text: group.text, obj: group}));
        }
	},

	populateGroups : function(){
		SGui.getGroups(this.cbPopulateGroups,this);
	},

	cbPopulateGroups : function(obj,result){
		obj.groups.removeAll();
		if(result)
		{
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateGroup(result[i]);
			} else {
				obj.updateGroup(result);
			}
		}
	},
	
	deleteGroup : function(){
		
		Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete the group?', function(btn)
		{
			if(btn == 'yes')
			{
				this.el.mask('Deleting Group...', 'x-mask-loading');
				SGui.removeGroup(this.groupSelected.id,this.cbDeleteGroup,this);
			}
		},this);
	},

	cbDeleteGroup : function(obj,result){
		obj.el.unmask();
		if(result)
		{
			if(result instanceof Array && result[0] == '-1')
			{
				Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
				return;
			}
			else if(result == '-1')
			{
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
				return;
			}

			var node = obj.getNodeById(obj.groupSelected.tid);
	        if(node){
	            node.unselect();
	            Ext.fly(node.ui.elNode).ghost('l', {callback: node.remove, scope: node, duration: .4 });
	        }
           	obj.fireEvent('noderemove', obj.groupSelected);
			obj.groupSelected = 0;
		}
	},

	showNewConfiguration : function(){
        if(!this.winConfiguration){
            this.winConfiguration = new ConfigurationWindow();
            this.winConfiguration.on('validconfiguration', this.cbConfiguration, this);
        }

        this.winConfiguration.show();
	},

	showEditConfiguration : function(){
        if(!this.winConfiguration){
            this.winConfiguration = new ConfigurationWindow();
            this.winConfiguration.on('validconfiguration', this.cbConfiguration, this);
        }

        this.winConfiguration.show(this.configurationSelected);
	},
	
	cbConfiguration : function(xml){
		this.updateConfiguration(xml);
       	this.fireEvent('nodereload', new Configuration(xml));
	},

	updateConfiguration : function(xml){
		var configuration = new Configuration(xml);
		var node = this.getNodeById(configuration.tid)
        if(node) {
        	node.setText(configuration.text);
        	node.attributes.obj = configuration;
        	this.configurationSelected = configuration;
        } else {
	        this.configurations.appendChild(new Ext.tree.TreeNode({ iconCls: 'configuration-icon', leaf:true, cls:'configuration-node', id: configuration.tid, text: configuration.text, obj: configuration}));
        }
	},

	populateConfigurations : function(){
		SGui.getConfigurations(this.cbPopulateConfigurations,this);
	},

	cbPopulateConfigurations : function(obj,result){
		obj.configurations.removeAll();
		if(result)
		{
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateConfiguration(result[i]);
			} else {
				obj.updateConfiguration(result);
			}
		}
	},
	
	deleteConfiguration : function(){
		
		Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete the configuration?', function(btn)
		{
			if(btn == 'yes')
			{
				this.el.mask('Deleting Configuration...', 'x-mask-loading');
				SGui.removeConfiguration(this.configurationSelected.id,this.cbDeleteConfiguration,this);
			}
		},this);
	},

	cbDeleteConfiguration : function(obj,result){
		obj.el.unmask();
		if(result)
		{
			if(result instanceof Array && result[0] == '-1')
			{
				Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
				return;
			}
			else if(result == '-1')
			{
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
				return;
			}

			var node = obj.getNodeById(obj.configurationSelected.tid);
	        if(node){
	            node.unselect();
	            Ext.fly(node.ui.elNode).ghost('l', {callback: node.remove, scope: node, duration: .4 });
	        }
           	obj.fireEvent('noderemove', obj.configurationSelected);
			obj.configurationSelected = 0;
		}
	},

	// prevent the default context menu when you miss the node
    afterRender : function(){
        ACSTree.superclass.afterRender.call(this);
        this.el.on('contextmenu', function(e){
            e.preventDefault();
        });
    }
});

Ext.reg('appfeedpanel', ACSTree); 
